import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 获取基础URL
String _getBaseUrl() {
  // 服务器实际地址
  const String serverHost = '10.0.2.2';
  const int serverPort = 9092;
  
  if (kIsWeb) {
    // Web平台：直接使用服务器地址
    return 'http://$serverHost:$serverPort';
  } else if (Platform.isAndroid) {
    // Android平台：检查是否为模拟器
    // 模拟器使用10.0.2.2访问宿主机，真机使用实际IP
    return 'http://10.0.2.2:$serverPort';
  } else if (Platform.isIOS) {
    // iOS模拟器：使用localhost，真机使用实际IP
    return 'http://localhost:$serverPort';
  } else {
    // 其他平台（macOS、Windows、Linux）：直接使用localhost
    return 'http://localhost:$serverPort';
  }
}

/// 网络服务提供者
final networkServiceProvider = Provider<NetworkService>((ref) {
  final baseUrl = _getBaseUrl();
  print('[NetworkService] 使用服务器地址: $baseUrl');
  
  final dio = Dio(BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 10),
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
      'Connection': 'close',
    },
  ));
  
  // 添加请求拦截器
  dio.interceptors.add(LogInterceptor(
    requestBody: true,
    responseBody: true,
    logPrint: (obj) => print('[NetworkService] $obj'),
  ));
  
  return NetworkService(dio);
});

/// 网络服务类
/// 负责处理所有HTTP请求，提供统一的网络接口
class NetworkService {
  final Dio _dio;

  NetworkService(this._dio);

  /// 将DateTime转换为简单日期格式，Java后台可以直接转换为Date对象
  String _formatDateToTimestamp(DateTime date) {
    // 使用简单日期格式 yyyy-MM-dd HH:mm:ss，Java后台可以直接解析
    return '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}';
  }

  /// 将DateTime转换为简单日期格式，Java后台可以直接转换为Date对象
  String _formatDateTimeToTimestamp(DateTime dateTime) {
    // 使用简单日期格式 yyyy-MM-dd HH:mm:ss，Java后台可以直接解析
    return '${dateTime.year.toString().padLeft(4, '0')}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}';
  }

  /// 通用GET请求
  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    try {
      print('[NetworkService] GET请求: $path');
      if (queryParameters != null) {
        print('[NetworkService] 查询参数: $queryParameters');
      }
      
      final response = await _dio.get<T>(
        path,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
      );
      
      print('[NetworkService] GET响应状态码: ${response.statusCode}');
      return response;
    } catch (e) {
      print('[NetworkService] GET请求失败: $e');
      rethrow;
    }
  }

  /// 通用POST请求
  Future<Response<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    try {
      print('[NetworkService] POST请求: $path');
      if (data != null) {
        print('[NetworkService] 请求数据: $data');
      }
      
      final response = await _dio.post<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
      );
      
      print('[NetworkService] POST响应状态码: ${response.statusCode}');
      return response;
    } catch (e) {
      print('[NetworkService] POST请求失败: $e');
      rethrow;
    }
  }

  /// 通用PUT请求
  Future<Response<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    try {
      print('[NetworkService] PUT请求: $path');
      if (data != null) {
        print('[NetworkService] 请求数据: $data');
      }
      
      final response = await _dio.put<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
      );
      
      print('[NetworkService] PUT响应状态码: ${response.statusCode}');
      return response;
    } catch (e) {
      print('[NetworkService] PUT请求失败: $e');
      rethrow;
    }
  }

  /// 通用DELETE请求
  Future<Response<T>> delete<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    try {
      print('[NetworkService] DELETE请求: $path');
      if (data != null) {
        print('[NetworkService] 请求数据: $data');
      }
      
      final response = await _dio.delete<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
      );
      
      print('[NetworkService] DELETE响应状态码: ${response.statusCode}');
      return response;
    } catch (e) {
      print('[NetworkService] DELETE请求失败: $e');
      rethrow;
    }
  }

  /// 财务相关API请求方法

  /// 获取月度账单列表
  Future<Response> getMonthlyBillList({
    required int year,
    required int userId,
  }) async {
    return await get(
      '/bill/month/list',
      queryParameters: {
        'year': year,
        'userId': userId,
      },
      options: Options(
        responseType: ResponseType.json,
        validateStatus: (status) => status! < 500,
        receiveTimeout: const Duration(seconds: 30),
        sendTimeout: const Duration(seconds: 10),
      ),
    );
  }

  /// 获取年度统计数据
  Future<Response> getYearlyStats({
    required int year,
    required int userId,
  }) async {
    return await get(
      '/bill/year/money',
      queryParameters: {
        'userId': userId,
        'year': year,
      },
      options: Options(
        responseType: ResponseType.json,
        validateStatus: (status) => status! < 500,
        receiveTimeout: const Duration(seconds: 30),
        sendTimeout: const Duration(seconds: 10),
      ),
    );
  }

  /// 获取交易记录列表
  Future<Response> getTransactionList({
    required int userId,
    DateTime? startDate,
    DateTime? endDate,
    String? category,
    String? type,
    int? page,
    int? pageSize,
  }) async {
    final queryParams = <String, dynamic>{
      'userId': userId,
    };
    
    if (startDate != null) {
      queryParams['startDate'] = _formatDateToTimestamp(startDate);
    }
    if (endDate != null) {
      queryParams['endDate'] = _formatDateToTimestamp(endDate);
    }
    if (category != null) {
      queryParams['category'] = category;
    }
    if (type != null) {
      queryParams['type'] = type;
    }
    if (page != null) {
      queryParams['page'] = page;
    }
    if (pageSize != null) {
      queryParams['pageSize'] = pageSize;
    }

    return await get(
      '/bill/list',
      queryParameters: queryParams,
    );
  }

  /// 创建交易记录
  Future<Response> createTransaction({
    required String userId,
    required String money,
    required String classifyId,
    required String secondClassifyId,
    required String createTime,
    required String updateTime,
    required int type,
  }) async {
    final data = {
      'userId': userId,
      'money': money,
      'classifyId': classifyId,
      'secondClassifyId': secondClassifyId,
      'createTime': createTime,
      'updateTime': updateTime,
      'type': type,
    };

    return await post(
      '/bill/save',
      data: data,
    );
  }

  /// 更新交易记录
  Future<Response> updateTransaction({
    required String transactionId,
    int? amount,
    String? type,
    String? category,
    String? description,
    DateTime? transactionDate,
  }) async {
    final data = <String, dynamic>{
      'transactionId': transactionId,
    };
    
    if (amount != null) data['amount'] = amount;
    if (type != null) data['type'] = type;
    if (category != null) data['category'] = category;
    if (description != null) data['description'] = description;
    if (transactionDate != null) {
      data['transactionDate'] = _formatDateTimeToTimestamp(transactionDate);
    }

    return await put(
      '/transaction/update',
      data: data,
    );
  }

  /// 删除交易记录
  Future<Response> deleteTransaction({
    required String transactionId,
  }) async {
    return await delete(
      '/transaction/delete',
      data: {'transactionId': transactionId},
    );
  }

  /// 获取分类统计
  Future<Response> getCategoryStats({
    required int userId,
    required String type,
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    final queryParams = <String, dynamic>{
      'userId': userId,
      'type': type,
    };
    
    if (startDate != null) {
      queryParams['startDate'] = _formatDateToTimestamp(startDate);
    }
    if (endDate != null) {
      queryParams['endDate'] = _formatDateToTimestamp(endDate);
    }

    return await get(
      '/transaction/category-stats',
      queryParameters: queryParams,
    );
  }

  /// 获取收支统计
  Future<Response> getIncomeExpenseStats({
    required int userId,
    DateTime? startDate,
    DateTime? endDate,
  }) async {
    final queryParams = <String, dynamic>{
      'userId': userId,
    };
    
    if (startDate != null) {
      queryParams['startDate'] = _formatDateToTimestamp(startDate);
    }
    if (endDate != null) {
      queryParams['endDate'] = _formatDateToTimestamp(endDate);
    }

    return await get(
      '/transaction/income-expense-stats',
      queryParameters: queryParams,
    );
  }

  /// 获取所有分类
  Future<Response> getAllCategories({
    required int userId,
  }) async {
    return await get(
      '/transaction/categories',
      queryParameters: {'userId': userId},
    );
  }

  /// 获取详细账单列表
  Future<Response> getBillDetailList({
    required int userId,
    required int type,
    required int secondClassifyId,
    required String date,
  }) async {
    return await get(
      '/bill/list',
      queryParameters: {
        'userId': userId,
        'type': type,
        'secondClassifyId': secondClassifyId,
        'date': date,
      },
      options: Options(
        responseType: ResponseType.json,
        validateStatus: (status) => status! < 500,
        receiveTimeout: const Duration(seconds: 30),
        sendTimeout: const Duration(seconds: 10),
      ),
    );
  }
}